Service

unique_toolkit.agentic_table.service.AgenticTableService

Provides methods to interact with the Agentic Table.

Attributes:

Name Type Description
#event ChatEvent

The ChatEvent object.

logger Optional[Logger]

The logger object. Defaults to None.

Source code in unique_toolkit/agentic_table/service.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
class AgenticTableService:
    """
    Provides methods to interact with the Agentic Table.

    Attributes:
        #event (ChatEvent): The ChatEvent object.
        logger (Optional[logging.Logger]): The logger object. Defaults to None.
    """

    def __init__(
        self,
        user_id: str,
        company_id: str,
        table_id: str,
        event_id: str | None = None,
        logger: logging.Logger = logging.getLogger(__name__),
    ):
        self._event_id = event_id
        self._user_id = user_id
        self._company_id = company_id
        self.table_id = table_id
        self.logger = logger

    async def set_cell(
        self,
        row: int,
        column: int,
        text: str,
        log_entries: list[LogEntry] | None = None,
    ):
        """
        Sets the value of a cell in the Agentic Table.

        Args:
            row (int): The row index.
            column (int): The column index.
            text (str): The text to set.
            log_entries (Optional[list[LogEntry]]): The log entries to set.
        """
        if log_entries is None:
            log_entries_new = []
        else:
            log_entries_new = [
                log_entry.to_sdk_log_entry() for log_entry in log_entries
            ]
        try:
            await AgenticTable.set_cell(
                user_id=self._user_id,
                company_id=self._company_id,
                tableId=self.table_id,
                rowOrder=row,
                columnOrder=column,
                text=text,
                logEntries=log_entries_new,
            )
        except Exception as e:
            self.logger.error(f"Error setting cell {row}, {column}: {e}.")

    async def get_cell(
        self, row: int, column: int, include_row_metadata: bool = True
    ) -> MagicTableCell:
        """
        Gets the value of a cell in the Agentic Table.

        Args:
            row (int): The row index.
            column (int): The column index.
            include_row_metadata (bool): Whether to include the row metadata. Defaults to True.

        Returns:
            MagicTableCell: The MagicTableCell object.

        """
        cell_data = await AgenticTable.get_cell(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            rowOrder=row,
            columnOrder=column,
            includeRowMetadata=include_row_metadata,  # type: ignore[arg-type]
        )
        return MagicTableCell.model_validate(cell_data)

    async def set_multiple_cells(
        self, cells: list[MagicTableCell], batch_size: int = 4000
    ):
        """
        Sets the values of multiple cells in the Agentic Table.

        Args:
            cells (list[MagicTableCell]): The cells to set sorted by row and column.
            batch_size (int): Number of cells to set in a single request.
        """
        for i in range(0, len(cells), batch_size):
            batch = cells[i : i + batch_size]
            await AgenticTable.set_multiple_cells(
                user_id=self._user_id,
                company_id=self._company_id,
                tableId=self.table_id,
                cells=[
                    SDKAgenticTableCell(
                        rowOrder=cell.row_order,
                        columnOrder=cell.column_order,
                        text=cell.text,
                    )
                    for cell in batch
                ],
            )

    async def set_activity(
        self,
        text: str,
        activity: MagicTableAction,
        status: ActivityStatus = ActivityStatus.IN_PROGRESS,
    ):
        """
        Sets the activity of the Agentic Table.

        Args:
            activity (str): The activity to set.
        """
        await AgenticTable.set_activity(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            activity=activity.value,  # type: ignore[arg-type]
            status=status.value,  # type: ignore[arg-type]
            text=text,
        )

    async def register_agent(self) -> None:
        """
        Registers the agent for the Agentic Table by updating the sheet state to PROCESSING.

        Raises:
            LockedAgenticTableError: If the Agentic Table is busy.
        """
        state = await AgenticTable.get_sheet_state(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
        )
        if state == AgenticTableSheetState.IDLE:
            await AgenticTable.update_sheet_state(
                user_id=self._user_id,
                company_id=self._company_id,
                tableId=self.table_id,
                state=AgenticTableSheetState.PROCESSING,
            )
            return
        # If the sheet is not idle, we cannot register the agent
        raise LockedAgenticTableError(
            f"Agentic Table is busy. Cannot register agent {self._event_id or self.table_id}."
        )

    async def deregister_agent(self):
        """
        Deregisters the agent for the Agentic Table by updating the sheet state to IDLE.

        Raises:
            LockedAgenticTableError: If the Agentic Table is busy.
        """
        await AgenticTable.update_sheet_state(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            state=AgenticTableSheetState.IDLE,
        )

    async def set_artifact(
        self,
        artifact_type: ArtifactType,
        content_id: str,
        mime_type: str,
        name: str,
    ):
        """Upload/set report files to the Agentic Table.

        Args:
            artifact_type (ArtifactType): The type of artifact to set.
            content_id (str): The content ID of the artifact.
            mime_type (str): The MIME type of the artifact.
            name (str): The name of the artifact.
        """
        await AgenticTable.set_artifact(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            artifactType=artifact_type.value,
            contentId=content_id,
            mimeType=mime_type,
            name=name,
        )

    @deprecated("Use set_column_style instead.")
    async def set_column_width(self, column: int, width: int):
        await self.set_column_style(column=column, width=width)

    async def set_column_style(
        self,
        column: int,
        width: int | None = None,
        cell_renderer: CellRendererTypes | None = None,
        filter: FilterTypes | None = None,
        editable: bool | None = None,
    ):
        """
        Sets the style of a column in the Agentic Table.

        Args:
            column (int): The column index.
            width (int | None, optional): The width of the column. Defaults to None.
            cell_renderer (CellRenderer | None, optional): The cell renderer of the column. Defaults to None.
            filter (FilterComponents | None, optional): The filter of the column. Defaults to None.
            editable (bool | None, optional): Whether the column is editable. Defaults to None.

        Raises:
            Exception: If the column style is not set.
        """
        # Convert the input to the correct format
        params = {}
        if width is not None:
            params["columnWidth"] = width
        if cell_renderer is not None:
            params["cellRenderer"] = cell_renderer.value
        if filter is not None:
            params["filter"] = filter.value
        if editable is not None:
            params["editable"] = editable
        status, message = await AgenticTable.set_column_metadata(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            columnOrder=column,
            **params,
        )
        if status:
            return
        raise Exception(message)

    async def get_num_rows(self) -> int:
        """
        Gets the number of rows in the Agentic Table.

        Returns:
            int: The number of rows in the Agentic Table.
        """
        sheet_info = await AgenticTable.get_sheet_data(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            includeRowCount=True,
            includeCells=False,
            includeLogHistory=False,
        )
        return sheet_info["magicTableRowCount"]

    async def get_sheet(
        self,
        start_row: int = 0,
        end_row: int | None = None,
        batch_size: int = 100,
        include_log_history: bool = False,
        include_cell_meta_data: bool = False,
        include_row_metadata: bool = False,
    ) -> MagicTableSheet:
        """
        Gets the sheet data from the Agentic Table paginated by batch_size.

        Args:
            start_row (int): The start row (inclusive).
            end_row (int | None): The end row (not inclusive).
            batch_size (int): The batch size.
            include_log_history (bool): Whether to include the log history.
            include_cell_meta_data (bool): Whether to include the cell metadata (renderer, selection, agreement status).
            include_row_metadata (bool): Whether to include the row metadata (key value pairs).
        Returns:
            MagicTableSheet: The sheet data.
        """
        # Find the total number of rows
        sheet_info = await AgenticTable.get_sheet_data(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            includeRowCount=True,
            includeCells=False,
            includeLogHistory=False,
            includeCellMetaData=False,
        )
        total_rows = sheet_info["magicTableRowCount"]
        if end_row is None or end_row > total_rows:
            end_row = total_rows
        if start_row > end_row:
            raise Exception("Start row is greater than end row")
        if start_row < 0 or end_row < 0:
            raise Exception("Start row or end row is negative")

        # Get the cells
        cells = []
        for row in range(start_row, end_row, batch_size):
            end_row_batch = min(row + batch_size, end_row)
            sheet_partial = await AgenticTable.get_sheet_data(
                user_id=self._user_id,
                company_id=self._company_id,
                tableId=self.table_id,
                includeCells=True,
                includeLogHistory=include_log_history,
                includeRowCount=False,
                includeCellMetaData=include_cell_meta_data,  # renderer, selection, agreement status
                startRow=row,
                endRow=end_row_batch - 1,
            )
            if "magicTableCells" in sheet_partial:
                if include_row_metadata:
                    # If include_row_metadata is true, we need to get the row metadata for each cell.
                    row_metadata_map = {}
                    # TODO: @thea-unique This routine is not efficient and would be nice if we had this data passed on in get_sheet_data.
                    for cell in sheet_partial["magicTableCells"]:
                        row_order = cell.get("rowOrder")  # type: ignore[assignment]
                        if row_order is not None and row_order not in row_metadata_map:
                            column_order = cell.get("columnOrder")  # type: ignore[assignment]
                            self.logger.info(
                                f"Getting row metadata for cell {row_order}, {column_order}"
                            )
                            cell_with_row_metadata = await self.get_cell(
                                row_order,
                                column_order,  # type: ignore[arg-type]
                            )
                            if cell_with_row_metadata.row_metadata:
                                print(cell_with_row_metadata.row_metadata)
                                row_metadata_map[cell_with_row_metadata.row_order] = (
                                    cell_with_row_metadata.row_metadata
                                )
                                cell["rowMetadata"] = (  # type: ignore[assignment]
                                    cell_with_row_metadata.row_metadata
                                )
                    # Assign row_metadata to all cells
                    for cell in sheet_partial["magicTableCells"]:
                        row_order = cell.get("rowOrder")  # type: ignore[assignment]
                        if row_order is not None and row_order in row_metadata_map:
                            cell["rowMetadata"] = row_metadata_map[  # type: ignore[assignment]
                                row_order
                            ]

                cells.extend(sheet_partial["magicTableCells"])

        sheet_info["magicTableCells"] = cells
        return MagicTableSheet.model_validate(sheet_info)

    async def get_sheet_metadata(self) -> list[RowMetadataEntry]:
        """
        Gets the sheet metadata from the Agentic Table.

        Returns:
            list[RowMetadataEntry]: The sheet metadata.
        """
        sheet_info = await AgenticTable.get_sheet_data(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            includeSheetMetadata=True,  # type: ignore[arg-type]
        )
        return [
            RowMetadataEntry.model_validate(metadata)
            for metadata in sheet_info["magicTableSheetMetadata"]
        ]

    async def set_cell_metadata(
        self,
        row: int,
        column: int,
        selected: bool | None = None,
        selection_method: SelectionMethod | None = None,
        agreement_status: AgreementStatus | None = None,
    ) -> None:
        """
        Sets the cell metadata for the Agentic Table.
        NOTE: This is not to be confused with the sheet metadata and is associated rather with selection and agreement status, row locking etc.

        Args:
            row (int): The row index.
            column (int): The column index.
            selected (bool | None): Whether the cell is selected.
            selection_method (SelectionMethod | None): The method of selection.
            agreement_status (AgreementStatus | None): The agreement status.
        """
        params = {}
        if selected is not None:
            params["selected"] = selected
        if selection_method is not None:
            params["selectionMethod"] = selection_method
        if agreement_status is not None:
            params["agreementStatus"] = agreement_status
        result = await AgenticTable.set_cell_metadata(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            rowOrder=row,
            columnOrder=column,
            **params,
        )
        if result["status"]:  # type: ignore
            return
        raise Exception(result["message"])  # type: ignore

    async def update_row_verification_status(
        self,
        row_orders: list[int],
        status: RowVerificationStatus,
    ):
        """Update the verification status of multiple rows at once.

        Args:
            row_orders (list[int]): The row indexes to update.
            status (RowVerificationStatus): The verification status to set.
        """
        await AgenticTable.bulk_update_status(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            rowOrders=row_orders,
            status=status,
        )

deregister_agent() async

Deregisters the agent for the Agentic Table by updating the sheet state to IDLE.

Raises:

Type Description
LockedAgenticTableError

If the Agentic Table is busy.

Source code in unique_toolkit/agentic_table/service.py
185
186
187
188
189
190
191
192
193
194
195
196
197
async def deregister_agent(self):
    """
    Deregisters the agent for the Agentic Table by updating the sheet state to IDLE.

    Raises:
        LockedAgenticTableError: If the Agentic Table is busy.
    """
    await AgenticTable.update_sheet_state(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        state=AgenticTableSheetState.IDLE,
    )

get_cell(row, column, include_row_metadata=True) async

Gets the value of a cell in the Agentic Table.

Parameters:

Name Type Description Default
row int

The row index.

required
column int

The column index.

required
include_row_metadata bool

Whether to include the row metadata. Defaults to True.

True

Returns:

Name Type Description
MagicTableCell MagicTableCell

The MagicTableCell object.

Source code in unique_toolkit/agentic_table/service.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
async def get_cell(
    self, row: int, column: int, include_row_metadata: bool = True
) -> MagicTableCell:
    """
    Gets the value of a cell in the Agentic Table.

    Args:
        row (int): The row index.
        column (int): The column index.
        include_row_metadata (bool): Whether to include the row metadata. Defaults to True.

    Returns:
        MagicTableCell: The MagicTableCell object.

    """
    cell_data = await AgenticTable.get_cell(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        rowOrder=row,
        columnOrder=column,
        includeRowMetadata=include_row_metadata,  # type: ignore[arg-type]
    )
    return MagicTableCell.model_validate(cell_data)

get_num_rows() async

Gets the number of rows in the Agentic Table.

Returns:

Name Type Description
int int

The number of rows in the Agentic Table.

Source code in unique_toolkit/agentic_table/service.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
async def get_num_rows(self) -> int:
    """
    Gets the number of rows in the Agentic Table.

    Returns:
        int: The number of rows in the Agentic Table.
    """
    sheet_info = await AgenticTable.get_sheet_data(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        includeRowCount=True,
        includeCells=False,
        includeLogHistory=False,
    )
    return sheet_info["magicTableRowCount"]

get_sheet(start_row=0, end_row=None, batch_size=100, include_log_history=False, include_cell_meta_data=False, include_row_metadata=False) async

Gets the sheet data from the Agentic Table paginated by batch_size.

Parameters:

Name Type Description Default
start_row int

The start row (inclusive).

0
end_row int | None

The end row (not inclusive).

None
batch_size int

The batch size.

100
include_log_history bool

Whether to include the log history.

False
include_cell_meta_data bool

Whether to include the cell metadata (renderer, selection, agreement status).

False
include_row_metadata bool

Whether to include the row metadata (key value pairs).

False
Source code in unique_toolkit/agentic_table/service.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
async def get_sheet(
    self,
    start_row: int = 0,
    end_row: int | None = None,
    batch_size: int = 100,
    include_log_history: bool = False,
    include_cell_meta_data: bool = False,
    include_row_metadata: bool = False,
) -> MagicTableSheet:
    """
    Gets the sheet data from the Agentic Table paginated by batch_size.

    Args:
        start_row (int): The start row (inclusive).
        end_row (int | None): The end row (not inclusive).
        batch_size (int): The batch size.
        include_log_history (bool): Whether to include the log history.
        include_cell_meta_data (bool): Whether to include the cell metadata (renderer, selection, agreement status).
        include_row_metadata (bool): Whether to include the row metadata (key value pairs).
    Returns:
        MagicTableSheet: The sheet data.
    """
    # Find the total number of rows
    sheet_info = await AgenticTable.get_sheet_data(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        includeRowCount=True,
        includeCells=False,
        includeLogHistory=False,
        includeCellMetaData=False,
    )
    total_rows = sheet_info["magicTableRowCount"]
    if end_row is None or end_row > total_rows:
        end_row = total_rows
    if start_row > end_row:
        raise Exception("Start row is greater than end row")
    if start_row < 0 or end_row < 0:
        raise Exception("Start row or end row is negative")

    # Get the cells
    cells = []
    for row in range(start_row, end_row, batch_size):
        end_row_batch = min(row + batch_size, end_row)
        sheet_partial = await AgenticTable.get_sheet_data(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            includeCells=True,
            includeLogHistory=include_log_history,
            includeRowCount=False,
            includeCellMetaData=include_cell_meta_data,  # renderer, selection, agreement status
            startRow=row,
            endRow=end_row_batch - 1,
        )
        if "magicTableCells" in sheet_partial:
            if include_row_metadata:
                # If include_row_metadata is true, we need to get the row metadata for each cell.
                row_metadata_map = {}
                # TODO: @thea-unique This routine is not efficient and would be nice if we had this data passed on in get_sheet_data.
                for cell in sheet_partial["magicTableCells"]:
                    row_order = cell.get("rowOrder")  # type: ignore[assignment]
                    if row_order is not None and row_order not in row_metadata_map:
                        column_order = cell.get("columnOrder")  # type: ignore[assignment]
                        self.logger.info(
                            f"Getting row metadata for cell {row_order}, {column_order}"
                        )
                        cell_with_row_metadata = await self.get_cell(
                            row_order,
                            column_order,  # type: ignore[arg-type]
                        )
                        if cell_with_row_metadata.row_metadata:
                            print(cell_with_row_metadata.row_metadata)
                            row_metadata_map[cell_with_row_metadata.row_order] = (
                                cell_with_row_metadata.row_metadata
                            )
                            cell["rowMetadata"] = (  # type: ignore[assignment]
                                cell_with_row_metadata.row_metadata
                            )
                # Assign row_metadata to all cells
                for cell in sheet_partial["magicTableCells"]:
                    row_order = cell.get("rowOrder")  # type: ignore[assignment]
                    if row_order is not None and row_order in row_metadata_map:
                        cell["rowMetadata"] = row_metadata_map[  # type: ignore[assignment]
                            row_order
                        ]

            cells.extend(sheet_partial["magicTableCells"])

    sheet_info["magicTableCells"] = cells
    return MagicTableSheet.model_validate(sheet_info)

get_sheet_metadata() async

Gets the sheet metadata from the Agentic Table.

Returns:

Type Description
list[RowMetadataEntry]

list[RowMetadataEntry]: The sheet metadata.

Source code in unique_toolkit/agentic_table/service.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
async def get_sheet_metadata(self) -> list[RowMetadataEntry]:
    """
    Gets the sheet metadata from the Agentic Table.

    Returns:
        list[RowMetadataEntry]: The sheet metadata.
    """
    sheet_info = await AgenticTable.get_sheet_data(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        includeSheetMetadata=True,  # type: ignore[arg-type]
    )
    return [
        RowMetadataEntry.model_validate(metadata)
        for metadata in sheet_info["magicTableSheetMetadata"]
    ]

register_agent() async

Registers the agent for the Agentic Table by updating the sheet state to PROCESSING.

Raises:

Type Description
LockedAgenticTableError

If the Agentic Table is busy.

Source code in unique_toolkit/agentic_table/service.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
async def register_agent(self) -> None:
    """
    Registers the agent for the Agentic Table by updating the sheet state to PROCESSING.

    Raises:
        LockedAgenticTableError: If the Agentic Table is busy.
    """
    state = await AgenticTable.get_sheet_state(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
    )
    if state == AgenticTableSheetState.IDLE:
        await AgenticTable.update_sheet_state(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            state=AgenticTableSheetState.PROCESSING,
        )
        return
    # If the sheet is not idle, we cannot register the agent
    raise LockedAgenticTableError(
        f"Agentic Table is busy. Cannot register agent {self._event_id or self.table_id}."
    )

set_activity(text, activity, status=ActivityStatus.IN_PROGRESS) async

Sets the activity of the Agentic Table.

Parameters:

Name Type Description Default
activity str

The activity to set.

required
Source code in unique_toolkit/agentic_table/service.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
async def set_activity(
    self,
    text: str,
    activity: MagicTableAction,
    status: ActivityStatus = ActivityStatus.IN_PROGRESS,
):
    """
    Sets the activity of the Agentic Table.

    Args:
        activity (str): The activity to set.
    """
    await AgenticTable.set_activity(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        activity=activity.value,  # type: ignore[arg-type]
        status=status.value,  # type: ignore[arg-type]
        text=text,
    )

set_artifact(artifact_type, content_id, mime_type, name) async

Upload/set report files to the Agentic Table.

Parameters:

Name Type Description Default
artifact_type ArtifactType

The type of artifact to set.

required
content_id str

The content ID of the artifact.

required
mime_type str

The MIME type of the artifact.

required
name str

The name of the artifact.

required
Source code in unique_toolkit/agentic_table/service.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
async def set_artifact(
    self,
    artifact_type: ArtifactType,
    content_id: str,
    mime_type: str,
    name: str,
):
    """Upload/set report files to the Agentic Table.

    Args:
        artifact_type (ArtifactType): The type of artifact to set.
        content_id (str): The content ID of the artifact.
        mime_type (str): The MIME type of the artifact.
        name (str): The name of the artifact.
    """
    await AgenticTable.set_artifact(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        artifactType=artifact_type.value,
        contentId=content_id,
        mimeType=mime_type,
        name=name,
    )

set_cell(row, column, text, log_entries=None) async

Sets the value of a cell in the Agentic Table.

Parameters:

Name Type Description Default
row int

The row index.

required
column int

The column index.

required
text str

The text to set.

required
log_entries Optional[list[LogEntry]]

The log entries to set.

None
Source code in unique_toolkit/agentic_table/service.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
async def set_cell(
    self,
    row: int,
    column: int,
    text: str,
    log_entries: list[LogEntry] | None = None,
):
    """
    Sets the value of a cell in the Agentic Table.

    Args:
        row (int): The row index.
        column (int): The column index.
        text (str): The text to set.
        log_entries (Optional[list[LogEntry]]): The log entries to set.
    """
    if log_entries is None:
        log_entries_new = []
    else:
        log_entries_new = [
            log_entry.to_sdk_log_entry() for log_entry in log_entries
        ]
    try:
        await AgenticTable.set_cell(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            rowOrder=row,
            columnOrder=column,
            text=text,
            logEntries=log_entries_new,
        )
    except Exception as e:
        self.logger.error(f"Error setting cell {row}, {column}: {e}.")

set_cell_metadata(row, column, selected=None, selection_method=None, agreement_status=None) async

Sets the cell metadata for the Agentic Table. NOTE: This is not to be confused with the sheet metadata and is associated rather with selection and agreement status, row locking etc.

Parameters:

Name Type Description Default
row int

The row index.

required
column int

The column index.

required
selected bool | None

Whether the cell is selected.

None
selection_method SelectionMethod | None

The method of selection.

None
agreement_status AgreementStatus | None

The agreement status.

None
Source code in unique_toolkit/agentic_table/service.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
async def set_cell_metadata(
    self,
    row: int,
    column: int,
    selected: bool | None = None,
    selection_method: SelectionMethod | None = None,
    agreement_status: AgreementStatus | None = None,
) -> None:
    """
    Sets the cell metadata for the Agentic Table.
    NOTE: This is not to be confused with the sheet metadata and is associated rather with selection and agreement status, row locking etc.

    Args:
        row (int): The row index.
        column (int): The column index.
        selected (bool | None): Whether the cell is selected.
        selection_method (SelectionMethod | None): The method of selection.
        agreement_status (AgreementStatus | None): The agreement status.
    """
    params = {}
    if selected is not None:
        params["selected"] = selected
    if selection_method is not None:
        params["selectionMethod"] = selection_method
    if agreement_status is not None:
        params["agreementStatus"] = agreement_status
    result = await AgenticTable.set_cell_metadata(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        rowOrder=row,
        columnOrder=column,
        **params,
    )
    if result["status"]:  # type: ignore
        return
    raise Exception(result["message"])  # type: ignore

set_column_style(column, width=None, cell_renderer=None, filter=None, editable=None) async

Sets the style of a column in the Agentic Table.

Parameters:

Name Type Description Default
column int

The column index.

required
width int | None

The width of the column. Defaults to None.

None
cell_renderer CellRenderer | None

The cell renderer of the column. Defaults to None.

None
filter FilterComponents | None

The filter of the column. Defaults to None.

None
editable bool | None

Whether the column is editable. Defaults to None.

None

Raises:

Type Description
Exception

If the column style is not set.

Source code in unique_toolkit/agentic_table/service.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
async def set_column_style(
    self,
    column: int,
    width: int | None = None,
    cell_renderer: CellRendererTypes | None = None,
    filter: FilterTypes | None = None,
    editable: bool | None = None,
):
    """
    Sets the style of a column in the Agentic Table.

    Args:
        column (int): The column index.
        width (int | None, optional): The width of the column. Defaults to None.
        cell_renderer (CellRenderer | None, optional): The cell renderer of the column. Defaults to None.
        filter (FilterComponents | None, optional): The filter of the column. Defaults to None.
        editable (bool | None, optional): Whether the column is editable. Defaults to None.

    Raises:
        Exception: If the column style is not set.
    """
    # Convert the input to the correct format
    params = {}
    if width is not None:
        params["columnWidth"] = width
    if cell_renderer is not None:
        params["cellRenderer"] = cell_renderer.value
    if filter is not None:
        params["filter"] = filter.value
    if editable is not None:
        params["editable"] = editable
    status, message = await AgenticTable.set_column_metadata(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        columnOrder=column,
        **params,
    )
    if status:
        return
    raise Exception(message)

set_multiple_cells(cells, batch_size=4000) async

Sets the values of multiple cells in the Agentic Table.

Parameters:

Name Type Description Default
cells list[MagicTableCell]

The cells to set sorted by row and column.

required
batch_size int

Number of cells to set in a single request.

4000
Source code in unique_toolkit/agentic_table/service.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
async def set_multiple_cells(
    self, cells: list[MagicTableCell], batch_size: int = 4000
):
    """
    Sets the values of multiple cells in the Agentic Table.

    Args:
        cells (list[MagicTableCell]): The cells to set sorted by row and column.
        batch_size (int): Number of cells to set in a single request.
    """
    for i in range(0, len(cells), batch_size):
        batch = cells[i : i + batch_size]
        await AgenticTable.set_multiple_cells(
            user_id=self._user_id,
            company_id=self._company_id,
            tableId=self.table_id,
            cells=[
                SDKAgenticTableCell(
                    rowOrder=cell.row_order,
                    columnOrder=cell.column_order,
                    text=cell.text,
                )
                for cell in batch
            ],
        )

update_row_verification_status(row_orders, status) async

Update the verification status of multiple rows at once.

Parameters:

Name Type Description Default
row_orders list[int]

The row indexes to update.

required
status RowVerificationStatus

The verification status to set.

required
Source code in unique_toolkit/agentic_table/service.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
async def update_row_verification_status(
    self,
    row_orders: list[int],
    status: RowVerificationStatus,
):
    """Update the verification status of multiple rows at once.

    Args:
        row_orders (list[int]): The row indexes to update.
        status (RowVerificationStatus): The verification status to set.
    """
    await AgenticTable.bulk_update_status(
        user_id=self._user_id,
        company_id=self._company_id,
        tableId=self.table_id,
        rowOrders=row_orders,
        status=status,
    )

Schemas

Event

The primary event type is MagicTableEvent.

unique_toolkit.agentic_table.schemas.MagicTableEvent

Bases: ChatEvent

Source code in unique_toolkit/agentic_table/schemas.py
222
223
224
class MagicTableEvent(ChatEvent):
    event: MagicTableEventTypes  # type: ignore[assignment]
    payload: MagicTablePayloadTypes  # type: ignore[assignment]

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

get_initial_debug_info()

Get the debug information for the chat event

Source code in unique_toolkit/app/schemas.py
261
262
263
264
265
266
267
268
269
270
def get_initial_debug_info(self) -> dict[str, Any]:
    """Get the debug information for the chat event"""

    # TODO: Make sure this coincides with what is shown in the first user message
    return {
        "user_metadata": self.payload.user_metadata,
        "tool_parameters": self.payload.tool_parameters,
        "chosen_module": self.payload.name,
        "assistant": {"id": self.payload.assistant_id},
    }

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

Event Payload Schemas

All event payloads inherit from the MagicTableBasePayload schema.

unique_toolkit.agentic_table.schemas.MagicTableBasePayload

Bases: BaseModel, Generic[A, T]

Source code in unique_toolkit/agentic_table/schemas.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class MagicTableBasePayload(BaseModel, Generic[A, T]):
    model_config = get_configuration_dict()
    name: str = Field(description="The name of the module")
    sheet_name: str

    action: A
    chat_id: str
    assistant_id: str
    table_id: str
    user_message: ChatEventUserMessage = Field(
        default=ChatEventUserMessage(
            id="", text="", original_text="", created_at="", language=""
        )
    )
    assistant_message: ChatEventAssistantMessage = Field(
        default=ChatEventAssistantMessage(id="", created_at="")
    )
    configuration: dict[str, Any] = {}
    metadata: T
    metadata_filter: dict[str, Any] | None = None

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

The following payload schemas correspond to the events listed above:

unique_toolkit.agentic_table.schemas.MagicTableUpdateCellPayload

Bases: MagicTableBasePayload[Literal[UPDATE_CELL], DDMetadata]

Source code in unique_toolkit/agentic_table/schemas.py
132
133
134
135
136
137
class MagicTableUpdateCellPayload(
    MagicTableBasePayload[Literal[MagicTableAction.UPDATE_CELL], DDMetadata]
):
    column_order: int
    row_order: int
    data: str

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.MagicTableAddMetadataPayload

Bases: MagicTableBasePayload[Literal[ADD_META_DATA], DDMetadata]

Source code in unique_toolkit/agentic_table/schemas.py
127
128
129
class MagicTableAddMetadataPayload(
    MagicTableBasePayload[Literal[MagicTableAction.ADD_META_DATA], DDMetadata]
): ...

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.MagicTableGenerateArtifactPayload

Bases: MagicTableBasePayload[Literal[GENERATE_ARTIFACT], BaseMetadata]

Source code in unique_toolkit/agentic_table/schemas.py
151
152
153
154
class MagicTableGenerateArtifactPayload(
    MagicTableBasePayload[Literal[MagicTableAction.GENERATE_ARTIFACT], BaseMetadata]
):
    data: ArtifactData

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.MagicTableSheetCompletedPayload

Bases: MagicTableBasePayload[Literal[SHEET_COMPLETED], SheetCompletedMetadata]

Source code in unique_toolkit/agentic_table/schemas.py
176
177
178
179
180
class MagicTableSheetCompletedPayload(
    MagicTableBasePayload[
        Literal[MagicTableAction.SHEET_COMPLETED], SheetCompletedMetadata
    ]
): ...

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.MagicTableLibrarySheetRowVerifiedPayload

Bases: MagicTableBasePayload[Literal[LIBRARY_SHEET_ROW_VERIFIED], LibrarySheetRowVerifiedMetadata]

Source code in unique_toolkit/agentic_table/schemas.py
199
200
201
202
203
204
class MagicTableLibrarySheetRowVerifiedPayload(
    MagicTableBasePayload[
        Literal[MagicTableAction.LIBRARY_SHEET_ROW_VERIFIED],
        LibrarySheetRowVerifiedMetadata,
    ]
): ...

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.MagicTableSheetCreatedPayload

Bases: MagicTableBasePayload[Literal[SHEET_CREATED], SheetCreatedMetadata]

Source code in unique_toolkit/agentic_table/schemas.py
186
187
188
class MagicTableSheetCreatedPayload(
    MagicTableBasePayload[Literal[MagicTableAction.SHEET_CREATED], SheetCreatedMetadata]
): ...

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

Supporting Schemas

unique_toolkit.agentic_table.schemas.BaseMetadata

Bases: BaseModel

Source code in unique_toolkit/agentic_table/schemas.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class BaseMetadata(BaseModel):
    model_config = get_configuration_dict()

    sheet_type: SheetType = Field(
        description="The type of the sheet.",
        default=SheetType.DEFAULT,
    )

    additional_sheet_information: dict[str, Any] = Field(
        default_factory=dict, description="Additional information for the sheet"
    )

    @field_validator("additional_sheet_information", mode="before")
    @classmethod
    def normalize_additional_sheet_information(cls, v):
        if v is None:
            return {}
        return v

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.DDMetadata

Bases: BaseMetadata

Source code in unique_toolkit/agentic_table/schemas.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class DDMetadata(BaseMetadata):
    model_config = get_configuration_dict()

    question_file_ids: list[str] = Field(
        default_factory=list, description="The IDs of the question files"
    )
    source_file_ids: list[str] = Field(
        default_factory=list, description="The IDs of the source files"
    )
    question_texts: list[str] = Field(
        default_factory=list, description="The texts of the questions"
    )
    context: str = Field(default="", description="The context text for the table.")

    @field_validator("context", mode="before")
    @classmethod
    def normalize_context(cls, v):
        if v is None:
            return ""
        return v

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.SheetCompletedMetadata

Bases: BaseMetadata

Source code in unique_toolkit/agentic_table/schemas.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
class SheetCompletedMetadata(BaseMetadata):
    model_config = get_configuration_dict()
    sheet_id: str = Field(description="The ID of the sheet that was completed.")
    library_sheet_id: str = Field(
        description="The ID of the library corresponding to the sheet."
    )
    context: str = Field(default="", description="The context text for the table.")

    @field_validator("context", mode="before")
    @classmethod
    def normalize_context(cls, v):
        if v is None:
            return ""
        return v

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.SheetCreatedMetadata

Bases: BaseMetadata

Source code in unique_toolkit/agentic_table/schemas.py
183
class SheetCreatedMetadata(BaseMetadata): ...

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.LibrarySheetRowVerifiedMetadata

Bases: BaseMetadata

Source code in unique_toolkit/agentic_table/schemas.py
194
195
196
class LibrarySheetRowVerifiedMetadata(BaseMetadata):
    model_config = get_configuration_dict()
    row_order: int = Field(description="The row index of the row that was verified.")

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.ArtifactData

Bases: BaseModel

Source code in unique_toolkit/agentic_table/schemas.py
146
147
148
class ArtifactData(BaseModel):
    model_config = get_configuration_dict()
    artifact_type: ArtifactType

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.ArtifactType

Bases: StrEnum

Source code in unique_toolkit/agentic_table/schemas.py
140
141
142
143
class ArtifactType(StrEnum):
    QUESTIONS = "QUESTIONS"
    FULL_REPORT = "FULL_REPORT"
    AGENTIC_REPORT = "AGENTIC_REPORT"

unique_toolkit.agentic_table.schemas.MagicTableCell

Bases: BaseModel

Source code in unique_toolkit/agentic_table/schemas.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
class MagicTableCell(BaseModel):
    model_config = get_configuration_dict()
    sheet_id: str
    row_order: int = Field(description="The row index of the cell.")
    column_order: int = Field(description="The column index of the cell.")
    row_locked: bool = Field(default=False, description="Lock status of the row.")
    text: str
    log_entries: list[LogEntry] = Field(
        default_factory=list, description="The log entries for the cell"
    )
    meta_data: MagicTableCellMetaData | None = Field(
        default=None, description="The metadata for the cell"
    )
    row_metadata: list[RowMetadataEntry] = Field(
        default_factory=list,
        description="The metadata (key value pairs)for the rows.",
    )

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.MagicTableSheet

Bases: BaseModel

Source code in unique_toolkit/agentic_table/schemas.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
class MagicTableSheet(BaseModel):
    model_config = get_configuration_dict()
    sheet_id: str
    name: str
    state: AgenticTableSheetState
    total_number_of_rows: int = Field(
        default=0,
        description="The total number of rows in the sheet",
        alias="magicTableRowCount",
    )
    chat_id: str
    created_by: str
    company_id: str
    created_at: str
    magic_table_cells: list[MagicTableCell] = Field(
        default_factory=list, description="The cells in the sheet"
    )
    magic_table_sheet_metadata: list[RowMetadataEntry] = Field(
        default_factory=list, description="The metadata for the sheet"
    )

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.LogEntry

Bases: BaseModel

Source code in unique_toolkit/agentic_table/schemas.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
class LogEntry(BaseModel):
    model_config = get_configuration_dict()

    text: str
    created_at: str
    actor_type: LanguageModelMessageRole
    message_id: str | None = None
    details: LogDetail | None = Field(
        default=None, description="The details of the log entry"
    )

    @field_validator("actor_type", mode="before")
    @classmethod
    def normalize_actor_type(cls, v):
        if isinstance(v, str):
            return v.lower()
        return v

    def to_sdk_log_entry(self) -> SDKLogEntry:
        params: dict[str, Any] = {
            "text": self.text,
            "createdAt": self.created_at,
            "actorType": self.actor_type.value.upper(),
        }
        if self.details:
            params["details"] = self.details.to_sdk_log_detail()

        return SDKLogEntry(**params)

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.LogDetail

Bases: BaseModel

Source code in unique_toolkit/agentic_table/schemas.py
227
228
229
230
231
232
233
234
235
236
237
class LogDetail(BaseModel):
    model_config = get_configuration_dict()
    llm_request: LanguageModelMessages | None = Field(
        default=None, description="The LLM request for the log detail"
    )

    def to_sdk_log_detail(self) -> SDKLogDetail:
        llm_request = None
        if self.llm_request:
            llm_request = self.llm_request.model_dump()
        return SDKLogDetail(llmRequest=llm_request)

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.agentic_table.schemas.RowMetadataEntry

Bases: BaseModel

Source code in unique_toolkit/agentic_table/schemas.py
64
65
66
67
68
69
70
71
72
class RowMetadataEntry(BaseModel):
    model_config = get_configuration_dict()
    id: str = Field(description="The ID of the metadata")
    key: str = Field(description="The key of the metadata")
    value: str = Field(description="The value of the metadata")
    exact_filter: bool = Field(
        default=False,
        description="Whether the metadata is to be used for strict filtering",
    )

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

Exceptions

unique_toolkit.agentic_table.service.LockedAgenticTableError

Bases: Exception

Source code in unique_toolkit/agentic_table/service.py
26
27
class LockedAgenticTableError(Exception):
    pass